package com.imast.android.bys.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class VolleySingleton {
	
	public static final String TAG = VolleySingleton.class.getSimpleName();
	
	private static VolleySingleton mInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mCtx;
 
    private VolleySingleton(Context context) {
        mCtx = context;
        mRequestQueue = getRequestQueue();
 
        mImageLoader = new ImageLoader(mRequestQueue,
                new ImageLoader.ImageCache() { 
            private final LruCache<String, Bitmap> 
                    cache = new LruCache<String, Bitmap>(20); 
 
            @Override 
            public Bitmap getBitmap(String url) {
                return cache.get(url);
            } 
 
            @Override 
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url, bitmap);
            } 
        }); 
    } 
    
    public static synchronized VolleySingleton getInstance() {
        return mInstance;
    } 
 
    public static synchronized VolleySingleton getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new VolleySingleton(context);
        } 
        return mInstance;
    } 
 
    public RequestQueue getRequestQueue() { 
        if (mRequestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the 
            // Activity or BroadcastReceiver if someone passes one in. 
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        } 
        return mRequestQueue;
    } 
 
    public <T> void addToRequestQueue(Request<T> req) {
    	req.setTag(TAG);
        getRequestQueue().add(req); 
    } 
    
    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
 
    public ImageLoader getImageLoader() { 
    	getRequestQueue();
        if (mImageLoader == null) {
            mImageLoader = new ImageLoader(this.mRequestQueue,
                    new LruBitmapCache());
        }
        return this.mImageLoader;
    } 

}
